package com.errands.cn.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "online", urlPatterns = {"/myOrder.html","/Take.html","/buy.html","/TakeOrder.html","/Send.html"})
public class OnlineFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(OnlineFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("用户登录过滤器启动 --->");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        if (session.getAttribute("user") == null) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                request.getSession().setAttribute("error","你还没有登录，没有权限执行该该操作，请先登录！");
                response.sendRedirect("/error.html");
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        logger.info("用户登录过滤器销毁 --->");
    }
}
